#-*- coding:utf-8 -*-
import os
import sys
import shutil
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from Widgets.rename import Rename
from Widgets.delete_warn import DeleteWarn
from Windows.CreateEpi import CreateEpi

class EpiWidget(QWidget):
    name_Signal = Signal(str)  # 当前选择的项目，发射信号
    del_Signal = Signal(str)  # 删除项目时发射的信号
    epiName_epiPath_shotList_Signal=Signal(tuple)#将当前集数真实路径以及该集下所有镜头列表发送出去
    epiName_epiPath_shotList_shot_Signal=Signal(list)#搜索返回信号，返回集数真实路径，所有镜头，以及选中的镜头名称
    def __init__(self):
        super(EpiWidget,self).__init__()

        # 全局变量
        # self.real_department_path=''
        self.real_epi_path=''
        self.mainLayout = QVBoxLayout()


        self.scrollArea = QScrollArea()  # 滚动窗口，需要添加self.scroll_widget进来

        self.scroll_widget = QWidget()  # 滚动窗口添加的内组件
        self.scroll_widget.setMinimumHeight(300)
        self.scroll_layout = QVBoxLayout()  # 滚动组件self.scroll_widget的布局，这里动态添加radiobutton

        self.scroll_layout.setAlignment(Qt.AlignTop)

        self.radio_epi_list = []  # 总的部门列表

        self.mainLayout.addWidget(self.scrollArea)

        self.setLayout(self.mainLayout)
        # 添加右击菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__rightMenu)

        self.current_project = ''
        self.current_department='' #当前部门
        self.current_real_department_path=''#当前真实部门路径
        self.current_epi=[]#''#当前集/场数
        self.current_real_epi_path=[]#''#当前真实集数路径
        self.check_box_list=[]#当前所有check_box

    def setCheckboxList(self,nameList):
        self.radio_epi_list = nameList
        try:
            for i in range(self.scroll_layout.count()):  # 先把以前的列表删除干净
                self.scroll_layout.itemAt(i).widget().deleteLater()
        except:
            pass
        self.check_box_list.clear()
        for i in nameList:
            checkbox=QCheckBox()
            checkbox.setText(i)
            checkbox.setStyleSheet("QCheckBox:hover{color :#FFC0CB}")
            checkbox.clicked.connect(self.__showNameSlot)
            self.scroll_layout.addWidget(checkbox)
            self.check_box_list.append(checkbox)

        self.scroll_widget.setLayout(self.scroll_layout)  # 添加布局
        self.scrollArea.setWidget(self.scroll_widget)


    def setRadioBtnList(self,nameList):
        self.radio_epi_list = nameList
        # if nameList==[]:
        try:
            for i in range(self.scroll_layout.count()):  # 先把以前的列表删除干净
                self.scroll_layout.itemAt(i).widget().deleteLater()
        except:
            pass

        for i in nameList:
            radio_btn = QRadioButton(i)
            radio_btn.setMinimumWidth(100)
            radio_btn.setStyleSheet("QRadioButton:hover{color :#FFC0CB}")
            radio_btn.clicked.connect(self.__showNameSlot)
            self.scroll_layout.addWidget(radio_btn)


        self.scroll_widget.setLayout(self.scroll_layout)  # 添加布局
        self.scrollArea.setWidget(self.scroll_widget)

    def setCurrentRadioBtn(self,epi_path,epi_name,current_shot_name):
        '''
        设置当前集数路径，搜索后刷新镜头
        :param epipath:
        :param epi:
        :return:
        '''

        for i in range(self.scroll_layout.count()):
            w=self.scroll_layout.itemAt(i).widget()
            if w.text()==epi_name:
                w.setChecked(True)

        self.current_real_epi_path =epi_path
        shot_list = os.listdir(self.current_real_epi_path)

        if shot_list != []:

            shot_info_list = []
            for i in shot_list:
                shot_info_dict = {}
                shot_dir_path = os.path.join(self.current_real_epi_path, i)
                shot_info_path = os.path.join(shot_dir_path, 'info')
                shot_info = self.__readInfo(shot_info_path)
                shot_info_dict[i] = shot_info
                shot_info_list.append(shot_info_dict)

            out_tuple = (self.current_real_epi_path, shot_list, shot_info_list,current_shot_name)

            self.epiName_epiPath_shotList_shot_Signal.emit(out_tuple)

        else:
            out_tuple = (self.current_real_epi_path, shot_list, [],'')
            self.epiName_epiPath_shotList_shot_Signal.emit(out_tuple)


    def setCurrentProjectName(self,projectName):
        '''
        该函数主要是用于在点击项目窗口后setCurrentProjectName设置主窗口全局变量的同时，让部门窗口也获取该值
        :param projectName:
        :return:
        '''
        self.current_project=projectName
    def setCurrentDepartment(self,department):
        '''
        传入当前选中的部门名称
        :param department:
        :return:
        '''
        self.current_department=department



    def setRealProjectPath(self,real_project_path):
        '''
        该函数为设置当前真实项目路径，主界面每次点击项目名称时发射过来
        :param real_project_path:
        :return:
        '''
        self.real_project_path=real_project_path

    def setRealDepartmentPath(self,real_department_path):
        '''
        层级越低，则需要传的东西越多，避免再次计算
        :param real_department_path:
        :return:
        '''
        self.current_real_department_path=real_department_path

    def deleteCurrentRadioBtn(self):
        '''
        因为是RadioButton所以除非一开始为空，必然选中的就是当前的，所以该方法可以直接调用
        :return:
        '''
        if self.current_epi is not '':
            self.radio_epi_list.remove(self.current_epi)
            for i in range(self.scroll_layout.count()):
                self.scroll_layout.itemAt(i).widget().deleteLater()
            self.__removeProject(self.current_epi)
            self.setRadioBtnList(self.radio_epi_list)
        else:
            QMessageBox.information(self, '提示', '请先选择集/场数')

    def __showNameSlot(self):
        '''
        最终集数函数，比较耗时，需要将该集数下所有的镜头信息列出来，发射结构为
        (self.current_real_epi_path,[shot_name1,shot_name2][{shot_name1:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx}},{shot_name2:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx}}])
        索引2是为了排序，索引3是为了方便后面指定查找
        :return:
        '''
        # btn = self.sender()
        # name = btn.text()
        # self.current_epi = name
        all_shot_list=[]
        shot_info_dict = {}
        shot_info_list = []
        self.current_epi.clear()
        self.current_real_epi_path.clear()
        for i in self.check_box_list:
            QCheckBox().isChecked()
            if i.isChecked():
                current_epi=i.text()
                current_real_epi_path=os.path.join(self.current_real_department_path,current_epi)
                self.current_epi.append(current_epi)
                self.current_real_epi_path.append(current_real_epi_path)

                shot_list=os.listdir(current_real_epi_path)

                if shot_list !=[]:
                    all_shot_list.extend(shot_list)
                    for i in shot_list:
                        shot_dir_path=os.path.join(current_real_epi_path,i)
                        shot_info_path=os.path.join(shot_dir_path,'info')
                        shot_info=self.__readInfo(shot_info_path)
                        shot_info_dict[i]=shot_info
                        shot_info_list.append(shot_info_dict)
        out_tuple=(self.current_real_epi_path,all_shot_list,shot_info_list)
        print(out_tuple)
        self.epiName_epiPath_shotList_Signal.emit(out_tuple)

        # else:
        #     out_tuple = (self.current_real_epi_path,shot_list,[])
        #     self.epiName_epiPath_shotList_Signal.emit(out_tuple)


    def renameBtn(self):
        '''
        打开重命名窗口rename.py,对本地项目信息以及真实项目目录进行重命名
        :return:
        '''
        if self.current_epi is '':
            QMessageBox.information(self, '提示', '请先选择集/场数')
        else:
            self.rename = Rename(self.current_epi)
            self.rename.newName_Signal.connect(self.__rename)
            self.rename.show()

            # pass

    def __rename(self, new_name):
        '''
        计算函数，对真实集数名称进行更改
        :param origin_name: 就是当前选中的集数
        :param new_name:
        :return: 注意改名完后，要刷新self.current_epi才行
        '''
        origin_name=self.current_epi
        origin_epi_path = os.path.join(self.real_department_path,self.current_epi)
        new_epi_path=os.path.join(self.real_department_path,new_name)
        temp_list=os.listdir(self.real_department_path)
        if origin_epi_path:  # 当存在时
            if new_name not in temp_list:
                try:
                    os.rename(origin_epi_path, new_epi_path)
                    temp_list.remove(self.current_epi)
                    temp_list.append(new_name)
                    self.current_epi = new_name
                    self.setRadioBtnList(temp_list)
                    QMessageBox.information(self, "提示", '{} 更名 {} 成功'.format(origin_name,new_name))
                except:
                    QMessageBox.information(self,"注意",'当前目录下有文件打开')




    def __rightMenu(self):
        self.menu = QMenu()

        self.addAction = QAction(u'添加集/场', self)
        self.addAction.triggered.connect(self.addBtn)
        self.menu.addAction(self.addAction)

        self.renameAction = QAction(u'重命名', self)
        self.renameAction.triggered.connect(self.renameBtn)
        self.menu.addAction(self.renameAction)

        self.deleteAction = QAction(u'删除', self)
        self.deleteAction.triggered.connect(self.__deleteBtn)
        self.menu.addAction(self.deleteAction)




        self.menu.exec_(QCursor.pos())


    def addBtn(self):
        '''
        添加集数，这里打开创建集数窗口

        :return:
        '''
        # print(self.current_department)
        if self.current_department !='':
            self.createEpiWindow=CreateEpi(self.current_real_department_path)
            self.createEpiWindow.epi_list_Signal.connect(self.setCheckboxList)
            self.createEpiWindow.show()
        else:
            QMessageBox.information(self,'提示','请先选择部门')






    def __deleteBtn(self):
        '''
        删除集/场按钮，直接删除真实路径下目录
        :return:
        '''
        self.dw=DeleteWarn(2)
        self.dw.out_Signal.connect(self.__real_delete)
        self.dw.show()

    def __real_delete(self,back):
        if back==1:
            btn = self.focusWidget()
            current_epi = btn.text()

            if current_epi in self.radio_epi_list:
                self.radio_epi_list.remove(current_epi)

                self.__removeEpi(current_epi)
                self.setRadioBtnList(self.radio_epi_list)
        else:
            print('返回0')
            pass

    def __removeEpi(self,epi):
        '''
        中间计算函数，不能用于外面调用
        :param name:
        :return:
        '''

        real_epi_path=os.path.join(self.current_real_department_path,epi)
        try:
            shutil.rmtree(real_epi_path,True)

        except:
            QMessageBox.information(self,"提示","该目录下有文件正被使用")




    def __readInfo(self,info_path):

        info=''
        with open(info_path,'r',encoding='utf-8') as r:
            read=r.read()
            info=eval(read)

        return info

if __name__ == '__main__':
    app = QApplication()
    E = EpiWidget()
    nameList = ['AAAAAAAAAAAAAAAAa', 'AAAAAAAAAb', 'c', 'd', 'e']
    E.setRadioBtnList(nameList)
    E.show()
    sys.exit(app.exec_())


